/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Chris
 */
import java.io.*;
import java.util.*;

public class DbStorage {

    public static void save(Hashtable<String, Hashtable<String, String>> db, String file) {

        try {

	BufferedWriter writer = new BufferedWriter(new FileWriter(file));
	
	for(String k : db.keySet()){
		
		for( String j : db.get(k).keySet()){
			writer.write(k+"|"+j+"|"+db.get(k).get(j)+"\n");
		}
	}
	writer.flush();
	writer.close();
	}
        catch (IOException e) {}

    }

    public static  Hashtable<String, Hashtable<String, String>> load(String file) {
        
         //load the database from file
        System.out.print("Loading datastore");

        Hashtable<String, Hashtable<String, String>> db = new Hashtable<String, Hashtable<String, String>>();

        try {
	BufferedReader reader = new BufferedReader(new FileReader(file));

	String line = "";
	Hashtable<String, String> innerContent = new Hashtable<String, String>();

	while((line = reader.readLine())!= null){
		
		String[] parts = line.split("|");

		if(db.containsKey(parts[0]))
			innerContent = db.get(parts[0]);
		else
			innerContent = new Hashtable<String, String>();

		innerContent.put(parts[1], parts[2]);

		db.put(parts[0], innerContent);	
	}
		
	reader.close();

        } catch (Exception e) {
            db = new Hashtable<String, Hashtable<String, String>>();
        }

        System.out.println("...done");

        return db;
    }
}
